﻿using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SGArchiveSystem7xDB.Linq
{
    public class T_ADDomainDal
    {
        static SGArchiveSystem7xEntities conn;
        /// <summary>
        /// 通过IP，用户名和密码，ou名获取AD域中的用户
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <param name="ouname"></param>
        /// <returns></returns>
        public static List<T_ADDomain> GetAndAdd_ADUSER(string ip, string username, string pwd, string ouname)
        {
            try
            {
                List<T_ADDomain> list = new List<T_ADDomain>();
                string[] or = ouname.Split(',');
                for(int i=0;i<or.Length;i++)
                {
                    DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + ip, username, pwd);//,"zs", "yu1234567.");
                    DirectoryEntry ou = adRoot.Children.Find("OU=" + or[i]);
                    DirectorySearcher mySearcher = new DirectorySearcher(ou);//想搜索出所有，此处可省参数
                    mySearcher.Filter = ("(objectClass=user)"); //user表示用户，group表示组
                    int count = mySearcher.FindAll().Count;
                    foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
                    {
                        DirectoryEntry user = resEnt.GetDirectoryEntry();
                        T_ADDomain en = new T_ADDomain();
                        en.AD_AccountName = user.Properties["sAMAccountName"][0].ToString();
                        en.AD_DisplayName = user.Properties["displayName"][0].ToString();
                        en.AD_OU = or[i];
                        if (user.Properties.Contains("description"))
                        {
                            en.AD_Description = user.Properties["description"][0].ToString();
                        }
                        if (user.Properties.Contains("telephoneNumber"))
                        {
                            en.AD_Telephone = user.Properties["telephoneNumber"][0].ToString();
                        }
                        if (user.Properties.Contains("mail"))
                        {
                            en.AD_Email = user.Properties["mail"][0].ToString();
                        }
                        if (user.Properties.Contains("c"))
                        {
                            en.AD_C = user.Properties["c"][0].ToString();//国家
                        }
                        if (user.Properties.Contains("st"))
                        {
                            en.AD_ST = user.Properties["st"][0].ToString();//省或自治区
                        }
                        if (user.Properties.Contains("l"))
                        {
                            en.AD_L = user.Properties["l"][0].ToString();//市
                        }
                        if (user.Properties.Contains("company"))
                        {
                            en.AD_Company = user.Properties["company"][0].ToString();//公司
                        }
                        if (user.Properties.Contains("department"))
                        {
                            en.AD_Department = user.Properties["department"][0].ToString();//部门
                        }
                        if (user.Properties.Contains("title"))
                        {
                            en.AD_Title = user.Properties["title"][0].ToString();//职务
                        }
                        list.Add(en);
                    }
                    Del_ADDomain(or[i]);
                    Add_ADDomain(list);
                }
                return list;
            }
            catch
            { return null; }
        }
        public static bool IsConnected(string domainName, string userName, string userPwd)
        {
            DirectoryEntry domain = new DirectoryEntry();
            try
            {
                domain.Path = string.Format("LDAP://{0}", domainName);
                domain.Username = userName;
                domain.Password = userPwd;
                domain.AuthenticationType = AuthenticationTypes.Secure;

                domain.RefreshCache();

                return true;
            }
            catch (Exception ex)
            {
                //LogRecord.WriteLog("[IsConnected方法]错误信息：" + ex.Message);
                return false;
            }
        }
        public static List<T_ADDomain> Get_ADDomain(out int count, string ouname,int start = -1, int row = -1)
        {
            count = 0;
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var query= conn.T_ADDomain.Select(c => c);
                if(ouname!=""&&ouname!=null)
                {
                    query = query.Where(c => c.AD_OU.Contains(ouname));
                }
                if (start != -1 && row != -1)
                {
                    count = query.Count();
                    return query.OrderBy(c => c.AD_ID).Skip(start).Take(row).ToList();
                }
                else
                {
                    var list = query.ToList();
                    count = list.Count;
                    return list;
                }
            }
            catch { return null; }
        }
        public static T_ADCONTENT Get_ADContent()
        {            
            try
            {
                conn = new SGArchiveSystem7xEntities();
                return conn.T_ADCONTENT.Select(c => c).Where(c=>c.ADC_ID==1).Single();
            }
            catch
            { return null; }
        }
        public static int Modify_ADContent(string ip, string username, string pwd, string ou)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var query= conn.T_ADCONTENT.Select(c => c).Where(c => c.ADC_ID == 1);
                foreach (var nn in query)
                {
                    nn.ADC_IP = ip;
                    nn.ADC_UNAME = username;
                    nn.ADC_PWD = pwd;
                    nn.ADC_OU = ou;
                }
                conn.SaveChanges();
                return 1;
            }
            catch
            { return -1; }
        }
        public static int Add_ADDomain(List<T_ADDomain> en)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                conn.T_ADDomain.AddRange(en);
                conn.SaveChanges();
                return 1;
            }
            catch (Exception ex)
            { return -1; }
        }
        public static int Del_ADDomain(string ouname)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var query = conn.T_ADDomain.Select(c => c).Where(c => c.AD_OU==ouname);
                conn.T_ADDomain.RemoveRange(query);
                conn.SaveChanges();
                return 1;
            }
            catch (Exception ex)
            { return -1; }
        }
        /// <summary>
        /// 同步用户
        /// </summary>
        /// <returns></returns>
        public static int TB_USER()
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var AD = conn.T_ADDomain.Select(c => c);
                var USER= conn.T_User.Select(c => c).Where(c=>c.U_AD==1);
                foreach (var nn in AD)
                {
                    var USERTABLE = USER.Where(c => c.U_NAME==nn.AD_AccountName);//去T_User查看是否存在
                    if (USERTABLE.Count() == 0)
                    {
                        T_User user = new T_User();
                        user.U_NAME = nn.AD_AccountName;
                        user.U_PWD = SGArchiveSystem7xCommons.PWD_MD5.MD5Encrypt("123456");
                        user.U_AD = 1;
                        user.U_RNAME = nn.AD_DisplayName;
                        user.U_STATUS = 1;
                        user.U_V04 = nn.AD_Telephone;
                        user.U_V01 = nn.AD_Email;
                        user.U_ISIP = 0;
                        user.U_IP = "";
                        //部门
                        T_UserDal.Add_User(user);
                    }
                }
                foreach (var nn in USER)
                {
                    var ADTABLE = AD.Where(c => c.AD_AccountName == nn.U_NAME);//去T_AD查看是否存在
                    if (ADTABLE.Count() == 0)
                    {
                        Modity_UserStatus(nn.U_ID);
                    }
                }
                return 1;
            }
            catch (Exception ex)
            { return -1; }
        }
        public static int Modity_UserStatus(int id)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var USER = conn.T_User.Select(c => c).Where(c => c.U_ID == id);
                foreach (var nn in USER)
                {
                    nn.U_STATUS = 0;
                }
                conn.SaveChanges();
                return 1;
            }
            catch (Exception ex)
            { return -1; }
        }
    }
}
